import globalStore from '../store/index.js'
const tui = {
	uploadUrl:'https://www.domain.com/api/upload/images',
	apiBsaeUrl:'https://www.domain.com/api',
	imgBaseUrl:'https://www.domain.com/attachment/',
	// 公众号中是否使用公众号授权登录 true公众号授权->auth界面下一步操作  false直接跳转login登录界面
	WECHAT_LOGIN: true,
	// 授权之后返回原有地址
	WECHAT_AUTH_BACK_URL:'WECHAT_AUTH_BACK_URL',
	apmapKey:'850d763e4fb3edc185f0ec93a793d173',
	// #ifdef H5
	jweixin:require('jweixin-module'),//微信h5开发使用
	// #endif
	toast: function(text, duration, success) {
		uni.showToast({
			title: text || "出错啦~",
			icon: success ? 'success' : 'none',
			duration: duration || 2000
		})
	},
	modal: function(title, content, showCancel, callback, confirmColor, confirmText) {
		uni.showModal({
			title: title || '提示',
			content: content,
			showCancel: showCancel,
			cancelColor: "#555",
			confirmColor: confirmColor || "#5677fc",
			confirmText: confirmText || "确定",
			success(res) {
				if (res.confirm) {
					callback && callback(true)
				} else {
					callback && callback(false)
				}
			}
		})
	},
	isAndroid: function() {
		const res = uni.getSystemInfoSync();
		return res.platform.toLocaleLowerCase() == "android"
	},
	isPhoneX: function() {
		const res = uni.getSystemInfoSync();
		let iphonex = false;
		let models=['iphonex','iphonexr','iphonexsmax','iphone11','iphone11pro','iphone11promax']
		const model=res.model.replace(/\s/g,"").toLowerCase()
		if (models.includes(model)) {
			iphonex = true;
		}
		return iphonex;
	},
	constNum: function() {
		let time = 0;
		// #ifdef APP-PLUS
		time = this.isAndroid() ? 300 : 0;
		// #endif
		return time
	},
	delayed: null,
	/**
	 * 请求数据处理
	 * @param string url 请求地址
	 * @param string method 请求方式
	 *  GET or POST
	 * @param {*} postData 请求参数
	 * @param bool isDelay 是否延迟显示loading
	 * @param bool isForm 数据格式
	 *  true: 'application/x-www-form-urlencoded'
	 *  false:'application/json'
	 * @param bool hideLoading 是否隐藏loading
	 *  true: 隐藏
	 *  false:显示
	 */
	request: function(url, method, postData, isDelay=1, isForm, hideLoading) {
		//接口请求
		let that = this
		console.log('每次请求校验商户参数',globalStore)
		let loadding = false;
		tui.delayed && uni.hideLoading();
		clearTimeout(tui.delayed);
		tui.delayed = null;
		if (!hideLoading) {
			console.log('不稍后了001')
			tui.delayed = setTimeout(() => {
				uni.showLoading({
					mask: true,
					title: '请稍候...',
					success(res) {
						console.log('不稍后了',res)
						loadding = true
					}
				})
			}, isDelay ? 1000 : 0)
		}
		console.log(tui.apiBsaeUrl + url,tui.bloc_id,tui.store_id,'isForm'+isForm,isForm ? 'application/x-www-form-urlencoded' : 'application/json')
		// if(tui.bloc_id){
		// 	url = url+'?bloc_id='+tui.bloc_id
		// }
		
		// if(tui.store_id){
		// 	url = url+'&store_id='+tui.store_id
		// }

		if(tui.getToken()){
			url = url+'?access-token='+tui.getToken()
		}	
		console.log('getToken',tui.getToken())
		return new Promise((resolve, reject) => {
			uni.request({
				url: tui.apiBsaeUrl + url,
				data: postData,
				header: {
					'Content-Type': isForm  ? 'application/json':'application/x-www-form-urlencoded',
					'access-token': tui.getToken(),
					'bloc-id':globalStore.state.bloc_id,
					'store-id':globalStore.state.store_id
				},
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					
					console.log('请求返回了了了',res)
					clearTimeout(tui.delayed)
					console.log('隐藏加载',loadding,hideLoading)
					tui.delayed = null;
					if (loadding && !hideLoading) {
						console.log('隐藏加载')
						uni.hideLoading()
					}
					
					if(res.data.name=="Unauthorized" && res.data.code==0){
						res.data.message = '登录失效，请重新登录'
						console.log('登录信息已失效01',res.data.name)
						console.log('登录信息已失效获取当前地址',window.location.href)
						
						tui.modal("登录提示", '请点击登录', false,() => {
							console.log('登录信息已失效02',res.data.name)
							//store.commit("logout") 登录页面执行
							
							// #ifdef MP-WEIXIN
								// 小程序
								tui.href('/pages/common/login/wechatlogin')
							// #endif
							
							
							// #ifdef H5
							let userAgent = navigator.userAgent;
							let _isWeixin = userAgent.toLowerCase().indexOf("micromessenger") !== -1
							let WECHAT_LOGIN = this.WECHAT_LOGIN
							console.log('_isWeixin',_isWeixin);
							if (_isWeixin && WECHAT_LOGIN) {// 公众号
								tui.wechatlogin()
							}else{//h5
								console.log('当前为H5环境')
								tui.href('/login')
							}
							
							// #endif
							
						},'','去登录')
						return
					}
					
					resolve(res.data)
				},
				fail: (res) => {
					clearTimeout(tui.delayed)
					tui.delayed = null;
					tui.toast("网络不给力，请稍后再试~")
					reject(res)
				},
				complete:(res)=>{
					uni.hideLoading()
				}
			})
		})
	},
	/**
	 * 上传文件
	 * @param string url 请求地址
	 * @param string src 文件路径
	 */
	uploadFile: function(src) {
		let that = this
		uni.showLoading({
			title: '请稍候...'
		})
		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url: tui.uploadUrl+'?access-token='+ tui.getToken(),
				filePath: src,
				name: 'file',
				// header: {
				// 	'Authorization': tui.getToken()
				// },
				formData: {
					'user': 'test'
				},
				success: function(res) {
					console.log(res)
					let img = JSON.parse(res.data)
					
					uni.hideLoading()
					console.log('图片上传',img,res)
					if (res.statusCode == 200) {
						//返回图片地址
						// let fileObj = img.attachment;
						resolve(img)
					} else {
						that.toast(res.msg);
					}
					// resolve(img)
				},
				fail: function(res) {
					console.log('错误',res)
					reject(res)
					that.toast(res.msg);
				}
			})
		})
	},
	tuiJsonp: function(url, callback, callbackname) {
		// #ifdef H5
		window[callbackname] = callback;
		let tuiScript = document.createElement("script");
		tuiScript.src = url;
		tuiScript.type = "text/javascript";
		document.head.appendChild(tuiScript);
		document.head.removeChild(tuiScript);
		// #endif
	},
	store: function(){
		let _this = this
		return new Promise((resolve, reject) => {
			tui.request("/store/info","GET",{store_id:globalStore.state.store_id}).then((res)=>{
				console.log(res)
				if (res.code == 200) {
					getApp().globalData.storeInfo = res.data
				}
				resolve(res.data)
			}).catch((res)=>{})
		})
		
	},
	/**
	 * 授权登录
	 */
	getUserInfo : function(callback) {
		  let _this = this
		  uni.showLoading({
			title: "正在登录",
			mask: true
		  });
		  // 执行微信登录
		  // 微信登录
		  uni.login({
			// provider: 'weixin',
			success: function (loginRes) {
				  console.log(loginRes,loginRes.authResult);
				  // 获取用户信息
				  uni.getUserInfo({
					provider: 'weixin',
					success: function (infoRes) {
						uni.showLoading();
						console.log('用户昵称为：' + infoRes.userInfo.nickName,infoRes.userInfo);
						_this.wechatsignup(infoRes,loginRes.code,callback)
						
					},
					fail(e) {
						console.log(e)
					}
				  });
			},
			fail(e) {
				console.log(e)
			}
		  });
	
	},
	// 微信登录
	wechatsignup:function(infoRes,code,callback){
				console.log(infoRes)
				// 获取用户token
				this.request("/wechat/basics/signup","POST",{
						code:code,
						avatarUrl:infoRes.userInfo.avatarUrl,
						nickname:infoRes.userInfo.nickName,
						gender:infoRes.userInfo.gender,
						country:infoRes.userInfo.country,
						city:infoRes.userInfo.city,
						province:infoRes.userInfo.province,
						openid:infoRes.userInfo.openId?infoRes.userInfo.openId:'',
						unionid:infoRes.userInfo.unionId?infoRes.userInfo.unionId:'',
					}).then((res)=>{
					console.log(res.data)
					if (res.code == 200) {
						uni.hideLoading();
						console.log('okok1',res.code,res)
						if(res.code==200){
							uni.setStorageSync('access_token', res.data.access_token);
							uni.setStorageSync('expiration_time', res.data.expiration_time);
							uni.setStorageSync('fans', res.data.fans);
							uni.setStorageSync('member', res.data.member);
							console.log(res);
							callback && callback();
						}
						
					} else {
						this.toast(res.message);
					}
				}).catch((res)=>{})
				
				
	},
	// 公众号登录
	wechatlogin:function(callback){
		let that = this
	
			// 微信公众号授权
			if (that.isLogin()) {
				console.log('微信公众号已授权')
				return false;
			}
			let  redirect_uri = encodeURIComponent(`${location.origin}/#/`)
			
			this.request("/officialaccount/basics/auth","POST",{
					redirect_uri:redirect_uri,
				}).then((res)=>{
				console.log(res.data)
				if (res.code == 200) {
					uni.hideLoading();
					console.log('okok1',res.code,res.data.headers.location[0])
					if(res.code==200){
						console.log('当前为公众号环境',decodeURI(res.data.headers.location[0]))
						location.href = decodeURI(res.data.headers.location[0])
						console.log(res);
						callback && callback();
					}
					
				} else {
					this.toast(res.message);
				}
			}).catch((res)=>{})
			
		
	},
	// 手机号登录
	mobileLogin:function(username,password,callback){
		let that = this
		this.request("/user/login","POST",{
			username:username,
			password:password
		}).then((res)=>{
			console.log('登录成功',res.data)
			if (res.code == 200) {
				uni.setStorageSync('access_token', res.data.access_token);
				uni.setStorageSync('expiration_time', res.data.expiration_time);
				uni.setStorageSync('fans', res.data.fans);
				uni.setStorageSync('member', res.data.member);
				console.log(res);
				callback && callback();
			} else {
				this.toast(res.message);
			}
		}).catch((res)=>{})
	},
	// h5初始化配置微信sdk
	initJssdk:function(callback){
		let that = this
		this.request("/officialaccount/jssdk/config","POST",{
			'url':`${location.origin}`+'/'
		}).then((res)=>{
			console.log('配置参数获取',res.data)
			if (res.code == 200) {
					that.jweixin.config(res.data)
					setTimeout(() => {
						callback && callback();
					}, 500);
			} else {
				this.toast(res.message);
			}
		}).catch((res)=>{
			console.log('initJssdk',res)
		})
	},
	getuserinfoBycode:function(code,callback){
		let that = this
		let  redirect_uri = encodeURIComponent(`${location.origin}`)
		this.request("/officialaccount/basics/userinfo","POST",{
				code:code
			}).then((res)=>{
			console.log(res.data)
			if (res.code == 200) {
				uni.setStorageSync('access_token', res.data.access_token);
				uni.setStorageSync('expiration_time', res.data.expiration_time);
				uni.setStorageSync('fans', res.data.fans);
				uni.setStorageSync('member', res.data.member);
				console.log(res);
				callback && callback(res);
			} else {
				this.toast(res.message);
			}
		}).catch((res)=>{})
	},
	wechatpay:function(body,order_no,pay_price,order_id,callback){
	   let _this = this;		  
	   let fans = uni.getStorageSync('fans');
	   console.log('订单支付信息组合',{
						openid:fans.openid,
						trade_type:'JSAPI',
						body:body,
						out_trade_no:order_no,
						total_fee:pay_price,
					})
		uni.showLoading()
		// 获取支付参数
		_this.request('/wechat/basics/payparameters',"POST",{
					openid:fans.openid,
					trade_type:'JSAPI',
					body:body,
					out_trade_no:order_no,
					total_fee:pay_price,
				}).then((parameters)=>{
				console.log('支付参数',parameters.code)
				if(parameters.code==200){
					uni.hideLoading()
					// 获取支付参数
					// #ifdef H5
					let userAgent = navigator.userAgent;
					let _isWeixin = userAgent.toLowerCase().indexOf("micromessenger") !== -1
					let WECHAT_LOGIN = this.WECHAT_LOGIN
					console.log('环境监测',_isWeixin,WECHAT_LOGIN)
					if (_isWeixin && WECHAT_LOGIN) {// 公众号
					
						console.log('sdkkokready')
						console.log('sdkk',_this.jweixin)
						_this.initJssdk(function(){
							console.log('微信配置参数初始化完成')
							_this.jweixin.ready(function(){  
								console.log('微信环境初始化完成',_this.jweixin)
								console.log('支付参数使用',parameters.data,parameters.data.timestamp)
							    // TODO
							    _this.jweixin.chooseWXPay({
							    	timestamp:parameters.data.timestamp,
							    	nonceStr: parameters.data.nonceStr,
							    	package: parameters.data.package,
							    	signType: parameters.data.signType,
							    	paySign: parameters.data.paySign,
							    	success: function (res) {
							    	// 支付成功后的回调函数
							    	  console.log('支付成功',res)
							    	  callback && callback(JSON.stringify(res));
							    	},
							    	fail:function(res){
										_this.toast(JSON.stringify(res));
							    		console.log('支付失败',res)
							    	}
							    });
							});  
						});
						
					}
					// #endif
					
					// #ifdef MP
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: parameters.data.timestamp,
						nonceStr: parameters.data.nonceStr,
						package: parameters.data.package,
						signType: parameters.data.signType,
						paySign: parameters.data.paySign,
						success: function (res) {
							console.log('success:' + JSON.stringify(res));
							console.log(parameters)
							callback && callback(JSON.stringify(res));
						},
						fail: function (err) {
							console.log('fail:' + JSON.stringify(err));
							let msg = err.errMsg=='requestPayment:fail cancel'?'取消支付':err.errMsg
							_this.toast(msg)
							uni.redirectTo({
								url:"order"
							})
						}
					});
					// #endif
					
				}else{
					_this.toast(parameters.message,3000,'error')
				}
			}).catch((err)=>{
				console.log("错误",err);
			});
		
		return false;
		
	},
	// 校验有效期
	checkCacheTime: function(keys){
		console.log(keys,'校验start')
		var timestamp = Date.parse(new Date());
		if(uni.getStorageSync(keys)==''){
			return true;
		}
		let cacheVal = uni.getStorageSync(keys).split('_');	
		let cacheValTime = cacheVal[cacheVal.length-1];
		let expiration_time= uni.getStorageSync('expiration_time');
		if(parseInt(cacheValTime)+parseInt(expiration_time)<=timestamp/1000){
			if(keys=='access_token'){
				// 缓存过期了
				uni.setStorageSync('access_token', '');
				uni.setStorageSync('fans', {});
				uni.setStorageSync('expiration_time',0);
				uni.setStorageSync('member',{});
			}else{
				uni.setStorageSync('keys', '');
			}
			console.log('过期了',cacheValTime,expiration_time,timestamp)
			return  true;
		}else{
			console.log('没过期',cacheValTime,expiration_time,timestamp)
			return  false;
		}
	},
	//设置用户信息
	setUserInfo: function(mobile, token) {
		uni.setStorageSync("access_token", token)
		uni.setStorageSync("thorui_mobile", mobile)
	},
	//获取token
	getToken() {
		return uni.getStorageSync("access_token")
	},
	//判断是否登录
	isLogin: function() {
		return uni.getStorageSync('access_token') != '' &&  uni.getStorageSync('access_token') != 'undefined' && !this.checkCacheTime('access_token');
		// return uni.getStorageSync('access_token') != '' && uni.getStorageSync('fans') != '' && !this.checkCacheTime('access_token');
	},
	getCitylist:function(callback){
		return new Promise((resolve, reject) => {
			this.request("/map/citylist","GET",{}).then((res)=>{
				console.log(res.data)
				if (res.code == 200) {
						uni.setStorageSync('Citylist', res.data);
						console.log(res);
						callback && callback(res.data)
				} else {
					this.toast(res.message);
				}
				resolve(res.data)
			}).catch((res)=>{
				reject(res)
			})
		})
	},
	//跳转页面，校验登录状态
	href(url, isVerify) {
		let that = this
		if (isVerify && !tui.isLogin()) {
			console.log(0,url)
			uni.navigateTo({
				url: '/login',
				complete(res) {
					console.log(res)
				}
			})
		} else {
			console.log(1,url)
			uni.navigateTo({
				url: url,
				complete(res) {
					console.log(res)
				}
			});
		}
	},
	getLocation(callback){
		let that = this;
		console.log('当前页面路径',`${location.origin}`)
		return new Promise((resolve, reject) => {
			// #ifdef H5
			let userAgent = navigator.userAgent;
			let _isWeixin = userAgent.toLowerCase().indexOf("micromessenger") !== -1
			let WECHAT_LOGIN = this.WECHAT_LOGIN
			console.log('环境监测',_isWeixin,WECHAT_LOGIN)
				
			if (_isWeixin && WECHAT_LOGIN) {// 公众号
				console.log('sdkkokready')
				console.log('sdkk',that.jweixin)
				that.initJssdk(function(){
					console.log('微信配置参数初始化完成')
					that.jweixin.getLocation({
					  type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
					  success: function (res) {
							var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
							var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
							var speed = res.speed; // 速度，以米/每秒计
							var accuracy = res.accuracy; // 位置精度
							// 请求了
							resolve(res.data)
							// 成功了 200
							callback && callback(res)
						
					  },
					  fail:function(res) {
						  console.log('公众号定位失败',res)
					  	// 错误了
					  	reject(res)
					  }
					});
					// that.jweixin.ready(function(){  
					//     // TODO
					   
					// });  
				});
				
			}else{
				uni.getLocation({
					type: 'wgs84',
					success:function(res){
						// 请求了
						resolve(res.data)
						
						// 成功了 200
						callback && callback(res)
						
					},
					fail:function(res) {
						// 错误了
						reject(res)
					}
				});
			}
			// #endif
		})
	},
	getQueryString(name)  {
		const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
		const search = window.location.search.split('?')[1] || '';
		const r = search.match(reg) || [];
		return r[2];
   }
}

export default tui
